package com.example.first.thread;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author LSQ
 * @Description 学习synchronized和CountDownLatch
 * @date 2021/9/23 23:39
 * @Version 1.0
 */

public class LearnSynchronized1 {

    private static final int CORE_POOL_SIZE = 50;
    private static final int MAX_POOL_SIZE = 50;
    private static final int QUEUE_CAPACITY = 100;
    private static final int TASK_COUNT = 100;

    public static int count = 0;

    // 加锁的情况
    // public static synchronized void compute(int costTime, String currentThreadName) {

    public static void compute(int costTime, String currentThreadName) {    // 不加锁的情况

        System.out.printf("[ %s ] is computing... %n", currentThreadName);

        // 每个线程对count 计算一万次
        for (int i = 0; i < 10000; i++) {

            count++;

        }
    }

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY));

        final CountDownLatch countDownLatch = new CountDownLatch(QUEUE_CAPACITY);


        for (int i = 0; i < QUEUE_CAPACITY; i++) {
            Random random = new Random();
            int taskExecuteTime = random.nextInt(10) + 1;

            int taskNum = i;
            Runnable runnable = () -> {
                String currentThreadName = Thread.currentThread().getName();

                System.out.println("[INFO] Before compute, thread is: " + currentThreadName);

                // 方法前面不加synchronized修饰，多个线程就会进去！
                compute(taskExecuteTime, currentThreadName);

                countDownLatch.countDown();
            };

            executorService.submit(runnable);

        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executorService.shutdown();

        System.out.println("Thread Pool shutdown!");
        System.out.println("Result: " + count);


    }

}


/*
        结论
          1、没加synchronized，计算结果 561043, 真实值1000000，差距还是很大！

        */
